import * as api from '@/services/checkTask';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { Checkbox, Col, Divider, Row, TreeSelect, message } from 'antd';
import React, { useRef, useState } from 'react';
import * as c from '@/services/consts';
import { ProFormSelect, ProFormText } from '@ant-design/pro-components';
import CheckServer from '@/components/CheckServer';
import { useModel } from 'umi';

type VpnServerFormProps = {
  visible: boolean;
  // groupIds: string[] | undefined;
  // instIds: number[] | undefined;
  // groups: API.VpnGroupMonitorModel[] | undefined;
  // servers: API.VpnServerMonitorModel[] | undefined;
  currentTask: API.CheckTask | undefined;
  onCancel: () => void;
  onSubmit: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, currentTask, onCancel, onSubmit } =
    props;

  if (!visible || !currentTask) {
    return null;
  }

  // console.log(groupIds, groups, instIds, servers);

  const formRef = useRef<ProFormInstance>();
  // const [myloading, setMyloading] = useState<boolean>(true);
  // const [dataSource, setDataSource] = useState<API.CheckTask | undefined>(undefined,);
  // const [dataCheckers, setDataCheckers] = useState<API.CheckServer[] | undefined>(undefined);
  // const [dataTemplets, setDataTemplets] = useState<API.NodeTemplate[] | undefined>(undefined);
  // const [changeCheckedList, setChangeCheckedList] = useState<any[]>([]);
  // const [checkedTempletList, setCheckedTempletList] = useState<any[]>([]);
  // const [checkJob, setCheckJob] = useState<string|undefined>('checknode');

  const [checkedList, setCheckedList] = useState<any[]>(currentTask.serverIds ?? []);
  const [checkeBlock, setCheckeBlock] = useState<boolean>(currentTask.checkBlock);
  // const [groupEditableKeys, setGroupEditableKeys] = useState<React.Key[]>(() =>groupIds.map((item) => item),);
  const [serverEditableKeys, setServerEditableKeys] = useState<React.Key[]>(() => currentTask.instanceIds?.map((item) => item),);
  const [selGroupIds, setSelGroupIds] = useState<string[] | undefined>(currentTask.groupIds);

  
  const { getVpnGroupExTrees, supplierOptions } = useModel('useGlobalModel', (model) => ({
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    supplierOptions: model.supplierOptions,
  }));

  // const editorFormRef = useRef<EditableFormInstance<API.VpnServerNet>>();
  // const loadData = async () => {
  //   let resultTemplet = await apiTemplate.all(undefined, undefined, undefined);
  //   if(resultTemplet && resultTemplet.success){
  //     setDataTemplets(resultTemplet.data);
  //   }
  //   setMyloading(false);
  // };

  // useEffect(() => {
  //   loadData();
  // }, []);

  const handleFormSubmit = async (record: API.CheckTaskForm) => {
    
    if(!checkedList || checkedList.length == 0){
      message.error("请选择用于检测的服务器");
      return;
    }
    // if(!job){
    //   message.error("请选择检测类型");
    //   return;
    // }
    if(!record.level){
      message.error("请选择检测级别");
      return;
    }

    record.serverIds = checkedList;
    record.recheckId = currentTask.id;
    record.instIds = serverEditableKeys.map((val) => val as number);
    record.job = c.CheckJob.HttpPost.value;
    record.checkBlock = checkeBlock;
    record.groupIds = selGroupIds;
    
    // console.log(record);
    // return;
    const result = await api.create(record);
    if (result && result.success) {
      onSubmit();
    }
  };
  

  const newServerColumns: ProColumns<API.VpnServerMonitorModel>[] = [
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      readonly: true,
      width: 200,
    },
    // {
    //   title: '名称',
    //   dataIndex: 'name',
    //   readonly: true,
    // },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];


  return (
    <DrawerForm<API.CheckTaskForm>
      open={visible}
      title='重新检测'
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      // submitter={{
      //   render: (props, defaultDoms) => {
      //     return [defaultDoms[0]];
      //   },
      // }}
      // loading={myloading}
      initialValues={currentTask}
    >
            <Row gutter={24} style={{marginTop:10}}>
              <Col span={4}>
                <ProFormSelect
                  name='level'
                  label="任务等级"
                  allowClear={false}
                  options={c.CheckLevelOptions}
                  mode='single'
                  initialValue={c.CheckLevel.Normal.value}
                />
              </Col>
              <Col span={3} style={{paddingTop:35}}>
                <Checkbox
                  checked={checkeBlock}
                  onChange={(e) => {
                    setCheckeBlock(e.target.checked);
                  }}
                >
                  检测被墙
                </Checkbox>
              </Col>
              <Col span={3} style={{paddingTop:30}}>
              </Col>
            </Row>

            <Row>
              <Col span={24} style={{marginBottom:-20}}>
                <ProFormText
                  name="name"
                  label="自定义名称"
                />
              </Col>
            </Row>

            <Divider orientation="left" orientationMargin={0}>检测服务器</Divider>
            <CheckServer onChange={setCheckedList} width={1100} initValues={checkedList} />

            
            {/* <Divider orientation="left" orientationMargin={0} style={{marginTop:40}}>节点模板</Divider>
            <Checkbox.Group key="ckgTemplet" onChange={setCheckedTempletList} value={checkedTempletList}>
              {dataTemplets?.map((gc) => {
                return (
                  <Checkbox value={gc.id} style={{ verticalAlign: 'middle' }}>
                    <Tag color='blue'>{gc.name}</Tag>
                  </Checkbox>
                );
              })}
            </Checkbox.Group> */}

            
      
            <Divider orientation="left" orientationMargin={0} style={{marginTop:20}}>分组</Divider>
            <Row gutter={24}>
              <Col span={24}>
                <TreeSelect
                  style={{ minWidth: '100%', marginTop: 0, marginBottom: 30 }}
                  listHeight={600}
                  // maxTagCount={1}
                  // dropdownMatchSelectWidth={false}
                  placeholder="选择分组"
                  allowClear={true}
                  showSearch={true}
                  treeCheckable={true}
                  // multiple={false}
                  treeDefaultExpandAll
                  treeData={getVpnGroupExTrees(undefined, true)}
                  value={selGroupIds}
                  treeNodeFilterProp="title"
                  onChange={(value) => {
                    setSelGroupIds(value ? value : undefined);
                  }}
                />
              </Col>
            </Row>
            
            <Divider orientation="left" orientationMargin={0}>服务器供应商</Divider>
            <Row gutter={24}>
              <Col span={24}>
                <ProFormSelect
                  name="supplierIds"
                  label=""
                  placeholder="请选择服务器供应商"
                  allowClear={true}
                  options={supplierOptions}
                  mode='multiple'
                  fieldProps={{
                    showArrow: true,
                    showSearch: true,
                    listHeight: 600,
                    // onChange: (value, option) => {
                    //   setSelSupplierIds(value);
                    // },
                  }}
                />
              </Col>
            </Row>
            
            {/* <Divider orientation="left" orientationMargin={0} style={{marginTop:40}}>检测分组</Divider>
            <EditableProTable<API.VpnGroupMonitorModel>
              rowKey="id"
              // editableFormRef={editorFormRef}
              // headerTitle="分组"
              locale={{ emptyText: '暂无数据' }}
              // toolBarRender={false}
              columns={newGroupColumns}
              defaultValue={groups}
              // onChange={setDataSource}
              recordCreatorProps={false}
              editable={{
                type: 'multiple',
                editableKeys: groupEditableKeys,
                actionRender: (row, config, defaultDom) => [
                  defaultDom.delete,
                ],
                // onValuesChange: (record, recordList) => {
                //   //setDataSource(recordList);
                // },
                onChange: setGroupEditableKeys,
              }}
            /> */}
            
            <Divider orientation="left" orientationMargin={0}>服务器</Divider>
            <EditableProTable<API.VpnServerMonitorModel>
              rowKey="instanceId"
              // headerTitle="服务器"
              locale={{ emptyText: '暂无数据' }}
              columns={newServerColumns}
              // defaultValue={currentTask.instanceIds?.map((val)=>({instanceId: val}))}
              recordCreatorProps={false}
              editable={{
                type: 'multiple',
                editableKeys: serverEditableKeys,
                actionRender: (row, config, defaultDom) => [
                  defaultDom.delete,
                ],
                onChange: setServerEditableKeys,
              }}
            />




    </DrawerForm>
  );
};

export default VpnServerForm;
